package parse;

import org.w3c.dom.*;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;

public class DOMParse {
    public static void main(String[] args) {
        // 创建DOM工厂,静态工厂创建对象
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        try {
            // 获取解析器
            DocumentBuilder builder = factory.newDocumentBuilder();
            // 解析文档
            Document document = builder.parse(DOMParse.class.getClassLoader().getResourceAsStream("students.xml"));
            // 此时的解析已经完成,可以根据解析出来的Document获取你想要的一切信息
            Element root = document.getDocumentElement();
            System.out.println("根标签:" + root.getTagName());
            System.out.println("no属性值:" + root.getAttribute("no"));

            // 获取指定元素的素有子节点
            NodeList childNodes = root.getChildNodes();
            System.out.println("子元素数量:" + childNodes.getLength());
            for (int i = 0; i < childNodes.getLength(); i++) {
                // 取出当前节点
                Node node = childNodes.item(i);
                // 此时子节点中存在文本节点与元素节点
                // 对于不同的节点,处理方式也不同
                // 需要判断当前节点类型
                if (node.getNodeType() == Node.ELEMENT_NODE) {
                    // 元素节点
                    Element ele = (Element) node;
                    System.out.println("标签名:" + ele.getTagName());
                    // 获取指定元素的所有属性
                    NamedNodeMap attributes = ele.getAttributes();
                    for (int j = 0; j < attributes.getLength(); j++) {
                        System.out.println(attributes.item(j));
                    }
                    // 获取子节点
                    NodeList children = ele.getChildNodes();
                    System.out.println(children.getLength());
                    for (int j = 0; j < children.getLength(); j++) {
                        Node child = children.item(j);
                        if (child.getNodeType() == Node.ELEMENT_NODE) {
                            Element name = (Element) child;
                            System.out.println(name.getTextContent());
                        }
                    }
                }
                if (node.getNodeType() == Node.TEXT_NODE) {
                    // 文本节点,打印文本内容
                    // System.out.println(node.getTextContent());
                }
            }

        } catch (ParserConfigurationException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (SAXException e) {
            throw new RuntimeException(e);
        }
    }
}
